package a66weding.com.jiehuntong.activity.me;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.AddressListBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeInvoiceMessageBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartDeleteBean;
import a66weding.com.jiehuntong.beans.OrderBeanIos;
import a66weding.com.jiehuntong.beans.OrderResultBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.MD5Util;
import a66weding.com.jiehuntong.common.utils.PopUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;

import static a66weding.com.jiehuntong.R.id.btn_me_compile;

/**
 * 这个是结算界面
 * Created by Administrator on 2016/7/29.
 */
public class MeCompileActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mProgressLay;
    private ViewGroup mContentLay;
    private LinearLayout mNoNetLay;
    private LinearLayout mBackLay;
    private LinearLayout mAddressLay;
    private LinearLayout mNoAddressLay;
    private LinearLayout mHaveAddressLay;
    private RelativeLayout mPayDistrbutionRay;
    private RelativeLayout mInvoiceMessageRay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private TextView mPayTv;
    private TextView mDistributionTv;
    private TextView mGoTimeTv;
    private TextView mNameTv;
    private TextView mPhoneTv;
    private TextView mAddressTv;
    private TextView mTotleCountTv;
    private TextView mTotleMoneyTv;
    private ExpandableListView mOrderListview;
    private Button mCommitBtn;
    private ArrayList<AddressListBean.DataBean> list;
    private List<MeShoppingCartBean.DataBean> shopSelectList;
    List<MeShoppingCartBean.DataBean.CartItemsBean> childSelectList;
    private AddressListBean addressListBean;
    private TextView mInvoiceTv;
    private MeShoppingCartBean shopBean;
    private MeShoppingCartBean selectshopBean;
    private int count;
    private MyExpandListAdapter mAdapter;
    private int addressId;
    private String peisongTime="双休日与节假日均可送货";
    private String payAway="在线支付";
    private String peisongDisc="快递配送";
    private int invoce=0;
    private int invocetype;
    private String invoiceTitle;
    private ArrayList<String> meArrayList = new ArrayList<>();
    private String cityName="北京";
    private float totalPrice = 0;//不含运费
    private float newTotalPrice;//含运费
    private static final int CITYDATASUCESS=1;
    public boolean isCleared;//防止用户多次创建提交订单
    private Handler mHandler =new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CITYDATASUCESS:
                    refreshView();
                    break;

            }
        }
    };
    private String nvc_name2="";
    private String nvc_name3="";
    private String nvc_name4="";
    private String nvc_name5="";
    private String nvc_name6="";
    private String nvc_name7="";
    private String nvc_name8="";
    private String nvc_name9="";
    private PopupWindow mCommitpop;
    private OrderResultBean.DataBean orderResultBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_compile);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeCompileActivity", this);
        // 向偏远地区添加元素
        meArrayList.add("内蒙古");meArrayList.add("河南省");
        meArrayList.add("广西省");meArrayList.add("海南省");
        meArrayList.add("云南省");meArrayList.add("西藏");
        meArrayList.add("甘肃省");meArrayList.add("青海省");
        meArrayList.add("宁夏");meArrayList.add("新疆");
        Intent intent = getIntent();
        if (intent != null) {
            Bundle cartBd = intent.getBundleExtra("cartBd");
            if (cartBd != null) {
                shopBean = (MeShoppingCartBean) cartBd.get("cartBean");//上个页面的购物车信息
/*---------这一段代码我感觉就像一个垃圾，复制了两三份购物车信息，实在是看不下去了，我不改了我只能写这么多备注了，祝你好运--------------------------*/
                selectshopBean = (MeShoppingCartBean) shopBean.clone();//复制一份购物车
                 List<MeShoppingCartBean.DataBean> shopList = shopBean.getData();//获得克隆版购物车中店铺以及商品
                List<MeShoppingCartBean.DataBean> selectList=new ArrayList<>();//所有店铺以及商品（这个名字虽然叫选中的商商铺，但是貌似没有做判断，纯属copy）
                childSelectList = new ArrayList<MeShoppingCartBean.DataBean.CartItemsBean>();//商品（这个名字虽然叫选中的商品，但是貌似没有做判断，纯属copy）
                for (int i = 0; i < shopList.size(); i++) {//遍历克隆版本的商品
                    MeShoppingCartBean.DataBean clone = (MeShoppingCartBean.DataBean) shopList.get(i).clone();//克隆版本中每个商铺的信息，以及商品
                    selectList.add(clone);//复制之以一份到
                    List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = shopList.get(i).getCartItems();//获得店铺所有商品信息
                    childSelectList=new ArrayList<MeShoppingCartBean.DataBean.CartItemsBean>();
                    for(int j=0;j<cartItems.size();j++){//遍历商品
                        childSelectList.add((MeShoppingCartBean.DataBean.CartItemsBean) cartItems.get(j).clone());
                    }
                    selectList.get(i).setCartItems(childSelectList);
                }
                selectshopBean.setData(selectList);
                if (selectshopBean != null) {
                    shopSelectList = new ArrayList<MeShoppingCartBean.DataBean>();
                    selectshopBean.getData();
                    boolean ischildcheck = false;
                    for (int i = 0; i < selectList.size(); i++) {
                        List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = selectList.get(i).getCartItems();
                        for (int j = 0; j < cartItems.size(); j++) {
                            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = cartItems.get(j);
                            if (cartItemsBean.isChildChecked()) {
                                count++;
                                ischildcheck = true;
                            } else {
                                cartItems.remove(cartItemsBean);
                                j--;
                            }
                        }
                        if (ischildcheck) {
                            shopSelectList.add(selectList.get(i));
                            ischildcheck = false;
                        }
                    }
                }
                /*---------------------------------------垃圾代码end---------------------------------------------------------*/
            }
        }
        initview();
        initData();
        isCleared=false;
        EventBus.getDefault().register(this);
    }
    /**
     * 页面初始化数据调用的方法
     */
    private void initData() {
        String url = UrlDealUtil.getRealUrlNewId(RequestCode.RETURN_ADDRESSISDEFAULT_1);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, AddressListBean.class, RequestCode.RETURN_ADDRESSISDEFAULT_1);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);
    }

    private void initview() {
        mNoNetLay = (LinearLayout) findViewById(R.id.NoNetLay);
        mProgressLay = (LinearLayout) findViewById(R.id.progressLay);
        mContentLay = (ViewGroup) findViewById(R.id.lay_content);
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mAddressLay = (LinearLayout) findViewById(R.id.ll_me_address);
        mNoAddressLay = (LinearLayout) findViewById(R.id.ll_me_no_address);
        mHaveAddressLay = (LinearLayout) findViewById(R.id.ll_me_have_address);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mPayTv = (TextView) findViewById(R.id.tv_me_pay);
        mDistributionTv = (TextView) findViewById(R.id.tv_me_distribution);
        mGoTimeTv = (TextView) findViewById(R.id.tv_me_gotime);
        mNameTv = (TextView) findViewById(R.id.tv_name);
        mPhoneTv = (TextView) findViewById(R.id.tv_phone);
        mAddressTv = (TextView) findViewById(R.id.tv_address);
        mPayDistrbutionRay = (RelativeLayout) findViewById(R.id.rl_me_pay_distrbution);
        mInvoiceMessageRay = (RelativeLayout) findViewById(R.id.rl_me_invoice_message);
        mCommitBtn = (Button) findViewById(btn_me_compile);
        mInvoiceTv = (TextView) findViewById(R.id.tv_me_invoice);
        mTotleCountTv = (TextView) findViewById(R.id.tv_me_total_number);
        mTotleMoneyTv = (TextView) findViewById(R.id.tv_total_money);
        mOrderListview = (ExpandableListView) findViewById(R.id.lview_orderList);
        mOrderListview.setGroupIndicator(null);
        mBackContentTv.setText("购物车");
        mHeaderTitleTv.setText("订单确认");
        mRightTitleTv.setVisibility(View.GONE);
        mPayTv.setText(payAway);
        mDistributionTv.setText(peisongDisc);
        mGoTimeTv.setText(peisongTime);
        mBackLay.setOnClickListener(this);
        mAddressLay.setOnClickListener(this);
        mPayDistrbutionRay.setOnClickListener(this);
        mInvoiceMessageRay.setOnClickListener(this);
        mCommitBtn.setOnClickListener(this);
        mTotleCountTv.setText("共"+count+"件");
        if (shopSelectList != null) {
            for (int i = 0; i < shopSelectList.size(); i++) {
                List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = shopSelectList.get(i).getCartItems();
                for (int j = 0; j < cartItems.size(); j++) {
                    double user_price = cartItems.get(j).getUser_price();
                    int quantity = cartItems.get(j).getQuantity();
                    totalPrice += quantity * user_price;
                }
            }
        }
    }
    private void refreshView(){
        if (shopSelectList != null) {
            mAdapter = new MyExpandListAdapter();
            mOrderListview.setAdapter(mAdapter);
            for (int i = 0; i < shopSelectList.size(); i++) {
                mOrderListview.expandGroup(i);
            }
        }
        float shipmentMoney=0;
        for (int i = 0; i < shopSelectList.size(); i++) {
            float shipmentMoney1 = shopSelectList.get(i).getShipmentMoney();
            shipmentMoney += shipmentMoney1;
        }
        newTotalPrice = StrUtil.floatNumDeal(totalPrice+shipmentMoney);
        mTotleMoneyTv.setText(String.valueOf(newTotalPrice));
        mOrderListview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
    }
    /**
     * 配送Event
     * @param event
     */
    @Subscribe
    public void onEvent(MePayDistributionActivity.MyPayEvent event) {
        if (event.pay != null && event.distrbution != null && event.goTime != null) {
            payAway = event.pay;
            peisongTime = event.goTime;
            peisongDisc = event.distrbution;
            mPayTv.setText(payAway);
            mDistributionTv.setText(peisongDisc);
            mGoTimeTv.setText(peisongTime);
        }
    }

    /**
     * 发票Event
     * @param event
     */
    @Subscribe
    public void onEvent(MeInvoiceMessageActivity.MyInvoiceEvent event) {
        if (event.invoice != null) {
            mInvoiceTv.setText(event.invoice);
            invoce = event.getInvoce();
            invocetype = event.getInvocetype();
            invoiceTitle = event.getInvoiceTitle();
            switch (invocetype) {
                case 0:
                    break;
                case 1:
                case 2:
                    nvc_name2 = event.getNvc_name2();
                    nvc_name3 = event.getNvc_name3();
                    nvc_name4 = event.getNvc_name4();
                    nvc_name5 = event.getNvc_name5();
                    nvc_name6 = event.getNvc_name6();
                    nvc_name7 = event.getNvc_name7();
                    nvc_name8 = event.getNvc_name8();
                    nvc_name9 = event.getNvc_name9();
                    break;
            }
        }
    }
    /**
     * 收货地址Event
     * @param event
     */
    @Subscribe
    public void onEvent(MeUserAddressActivity.MyAddressEvent event) {
        if (event != null) {
            mHaveAddressLay.setVisibility(View.VISIBLE);
            mNoAddressLay.setVisibility(View.GONE);
            AddressListBean.DataBean addressBean = event.getAddressBean();
            mNameTv.setText(addressBean.getNvc_Consignee());
            mPhoneTv.setText(addressBean.getNvc_MobilePhone());
            String address = addressBean.getPName() + addressBean.getCName() +
                    addressBean.getAName() + addressBean.getNvc_StreetAddress();
            mAddressTv.setText(address);
            addressId = addressBean.getI_Id();
            // 设置地址
            cityName = addressBean.getPName();
            mHandler.sendEmptyMessage(CITYDATASUCESS);
        }
    }
    /**
     * 当界面销毁的时候,把发票信息界面的数据全部置为空
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        MeInvoiceMessageBean.setMeInvoice(null);
        MeInvoiceMessageBean.setMeInvoice1(null);
        MeInvoiceMessageBean.setMeInvoice2(null);
        MeInvoiceMessageBean.setMeInvoice3(null);
        MeInvoiceMessageBean.setMeInvoice4(null);
        MeInvoiceMessageBean.setMeInvoice5(null);
        MeInvoiceMessageBean.setMeInvoice6(null);
        MeInvoiceMessageBean.setMeInvoice7(null);
        MeInvoiceMessageBean.setMeInvoice8(null);
        MeInvoiceMessageBean.setMeInvoice9(null);
        MeInvoiceMessageBean.setMeInvoice10(null);
    }
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.lay_head_backlay: //点击购物车，返回到上一级界面
                Intent intent1 = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("cartBean",shopBean);
                intent1.putExtras(bundle);
                setResult(MeShoppingCartActivity.startForResult,intent1);
                finish();
                break;
            case R.id.ll_me_address: //地址
                intent.setClass(this, MeUserAddressActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_me_pay_distrbution: //支付配送方式
                intent.setClass(this, MePayDistributionActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_me_invoice_message: //发票信息
                intent.setClass(this, MeInvoiceMessageActivity.class);
                startActivity(intent);
                break;
            case btn_me_compile: //支付界面或者是线下付款界面(提交订单)
                if (isCleared){
                CUtils.showToastInCenter("该订单已生成，请勿重复提交订单！");
                    mCommitBtn.setEnabled(false);
                }else {
                    boolean isCanCommit = checkInfo();
                    if (!isCanCommit) {
                        return;
                    }
                    mCommitpop = PopUtils.showCommitPop(this, v);
                    createOrder();
                }
                break;
        }
    }
    private boolean checkInfo() {
        String addressTv = mAddressTv.getText().toString().trim();
        if(TextUtils.isEmpty(addressTv)) {
            CUtils.showToast( "请设置收货地址！");
            return false;
        }
        String nameTv = mNameTv.getText().toString().trim();
        if(TextUtils.isEmpty(nameTv)) {
            CUtils.showToast( "收货人不能为空");
            return false;
        }
        String phoneTv = mPhoneTv.getText().toString().trim();
        if(TextUtils.isEmpty(phoneTv)) {
            CUtils.showToast( "收货人联系方式不能为空");
            return false;
        }
        return true;
    }
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        refreshViewLay(HAVEDATA,mContentLay,mProgressLay,mNoNetLay);
        if (data instanceof AddressListBean) {
            addressListBean = (AddressListBean) data;
            switch (addressListBean.getResCode()) {
                case "0000":
                    mNoAddressLay.setVisibility(View.GONE);
                    mHaveAddressLay.setVisibility(View.VISIBLE);
                    list = (ArrayList<AddressListBean.DataBean>) addressListBean.getData();
                    if (list == null) {
                        mHaveAddressLay.setVisibility(View.GONE);
                        mNoAddressLay.setVisibility(View.VISIBLE);
                        CUtils.showToast("您还没有设置过收货地址，请设置收货地址");
                    }else{
                        int s = 0;  // 设置这个变量是为了操作,有收货地址但是没有默认收货
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getIsDefault() == 1) {
                                mNameTv.setText(list.get(i).getNvc_Consignee());
                                mPhoneTv.setText(list.get(i).getNvc_MobilePhone());
                                mAddressTv.setText(list.get(i).getPName() + list.get(i).getCName() +
                                        list.get(i).getAName() + list.get(i).getNvc_StreetAddress());
                                addressId = list.get(i).getI_Id();
                                cityName = list.get(i).getPName();
                                s = 1;  // 如果有默认收货地址,就将变量设置成1
                            }
                            if (s == 0){ //如果没有默认收货地址,就把地址中的第一条数据设置上
                                mNameTv.setText(list.get(0).getNvc_Consignee());
                                mPhoneTv.setText(list.get(0).getNvc_MobilePhone());
                                mAddressTv.setText(list.get(0).getPName() + list.get(0).getCName() +
                                        list.get(0).getAName() + list.get(0).getNvc_StreetAddress());
                                addressId = list.get(0).getI_Id();
                                cityName = list.get(0).getPName();
                            }
                        }
                    }
                    break;
                case "0003":
                    mHaveAddressLay.setVisibility(View.GONE);
                    mNoAddressLay.setVisibility(View.VISIBLE);
                    CUtils.showToast("您还没有设置过收货地址，请设置收货地址");
                    break;
            }
            mHandler.sendEmptyMessage(CITYDATASUCESS);
        }else {
            if (data instanceof OrderResultBean) {
                OrderResultBean orderData = (OrderResultBean) data;
                if (mCommitpop != null) {
                    mCommitpop.dismiss();
                }
                switch (orderData.getResCode()) {
                    case "0000":
                        Log.i("提交订单成功", "onSucess: ");
                        deleteGoods();//订单提交成功后从购物车中删除该商品
                        orderResultBean = orderData.getData();
                        double dm_totalMoney = orderResultBean.getOrder().getDm_TotalMoney();
                        float resultTotalMoney = StrUtil.floatNumDeal((float) dm_totalMoney);
                        if (newTotalPrice == resultTotalMoney) {
                            startPayActivity();
                        } else {
                            CUtils.showToast("数据校验失败，请稍后重试");
                        }
                        break;
                }
            }
        }if (data instanceof MeShoppingCartDeleteBean) {
            MeShoppingCartDeleteBean  meShoppingCartDeleteBean = (MeShoppingCartDeleteBean) data;
            switch (meShoppingCartDeleteBean.getResCode()) {
                case "0000":
                    Log.i("订单生成成功后购物车移除完毕", "onSucess: ");
                    Intent intent2 = new Intent();
                    intent2.setAction("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
                    //发送无序广播通知分类刷新当前购物车数量
                    sendBroadcast(intent2);
                    break;
                case "0005":
                    break;
            }

        }


    }
    /**
     * 当订单创建成功后，从购物车中移除改商品
     */
    private void deleteGoods() {
        if (shopBean!= null) {
            StringBuffer buffer = new StringBuffer();
            //获取整个购物车
            for (int i = 0; i < shopBean.getData().size(); i++) {//遍历整个购物车的商家
                List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = shopBean.getData().get(i).getCartItems();//获得商家所有购物车商品

                for (int j = 0; j < cartItems.size(); j++) {//遍历全部产品
                    if (cartItems.get(j).isChildChecked()) {//如果产品是选中状态
                        String id = String.valueOf(cartItems.get(j).getGoods_id());//获得商品id
                        buffer.append(id + ",");//拼接id
                    }
                }
            }
            String str = buffer.toString();//拼接后的id
            String ids = str.substring(0, str.length() - 1);//拼接后多一个 ","截取删除
            isCleared=true;
            //联网从购物车中删除
            String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
            String url = oldUrl + "&productID=" + ids;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    MeCompileActivity.this, MeShoppingCartDeleteBean.class, RequestCode.DELSHOPSBYPRODUCTIDANDMEMBER);
            HttpHandleUtil.executeCommonPost(MeCompileActivity.this, httpRequestBean);
        }
    }
    @Override
    public void onError(ErrorBean errorBean) {
        if(mCommitpop!=null) {
            mCommitpop.dismiss();
        }
        switch (errorBean.getErrorCode()) {
            case ErrorBean.TIMEOUT:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            case ErrorBean.NONET:
                refreshViewLay(NONET,mContentLay,mProgressLay,mNoNetLay);
                break;
            default:
                CUtils.showDataErrToast(this);
        }
    }

    public class MyExpandListAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return shopSelectList.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = shopSelectList.get(groupPosition).getCartItems();

            return mscData.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return shopSelectList.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = null;
            MeShoppingCartBean.DataBean dataBean = shopSelectList.get(groupPosition);
            if (dataBean != null) {
                cartItemsBean = dataBean.getCartItems().get(childPosition);
            }
            return cartItemsBean;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {

            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            MeShoppingCartBean.DataBean dataBean = shopSelectList.get(groupPosition);
            GroupHolder mHolder;
            if (convertView != null) {
                mHolder = (GroupHolder) convertView.getTag();
            } else {
                convertView = View.inflate(getApplicationContext(), R.layout.item_me_indent_shoppingorder_group, null);
                mHolder = new GroupHolder();
                mHolder.mShopingNameTv = (TextView) convertView.findViewById(R.id.tv_me_shopping_order_title);
                convertView.setTag(mHolder);
            }

            List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = dataBean.getCartItems();

            mHolder.mShopingNameTv.setText(dataBean.getBusinessName());

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            MeShoppingCartBean.DataBean dataBean = shopSelectList.get(groupPosition);
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = dataBean.getCartItems();
            MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = mscData.get(childPosition);

            ItemHolder mHolder;
            if (convertView != null) {
                mHolder = (ItemHolder) convertView.getTag();
            } else {
                convertView = View.inflate(getApplicationContext(), R.layout.item_me_indent_shopping_orderchild, null);
                mHolder = new ItemHolder();

                mHolder.mIndentIv = (ImageView) convertView.findViewById(R.id.img_indent);
                mHolder.mShopingCartTitleTv = (TextView) convertView.findViewById(R.id.tv_indent_childname);
                mHolder.mStandardTv = (TextView) convertView.findViewById(R.id.tv_me_standard);
                mHolder.mShowMoneyTv = (TextView) convertView.findViewById(R.id.tv_money);
                mHolder.myOldMoney = (TextView) convertView.findViewById(R.id.tv_me_old_money);
                mHolder.mNumberTv = (TextView) convertView.findViewById(R.id.tv_me_number);
                mHolder.mGroupAccontLay = (LinearLayout) convertView.findViewById(R.id.llay_group_Accont);
                convertView.setTag(mHolder);
            }
            convertView.setVisibility(View.VISIBLE);
            x.image().bind(mHolder.mIndentIv, cartItemsBean.getImg_url());
            mHolder.mShopingCartTitleTv.setText(cartItemsBean.getTitle());
            mHolder.mShowMoneyTv.setText(" ¥ " + String.valueOf(cartItemsBean.getUser_price()));
            mHolder.myOldMoney.setText(" ¥ " + String.valueOf(cartItemsBean.getSell_price()));
            mHolder.myOldMoney.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            // 设置数量
            mHolder.mNumberTv.setText("数量: " + cartItemsBean.getQuantity());
            if (isLastChild) {
                mHolder.mGroupAccontLay.setVisibility(View.VISIBLE);
                TextView freightGrouppriceAccont = (TextView) mHolder.mGroupAccontLay.findViewById(R.id.tv_order_groupAccont_freight);
                freightGrouppriceAccont.setText(" ¥ " +  dataBean.getShipmentMoney());
                // 获取到商品价格
                float groupPrice = 0;
                for (int i = 0; i < mscData.size(); i++) {
                    double user_price1 = mscData.get(i).getUser_price();
                    int quantity = mscData.get(i).getQuantity();
                    groupPrice += user_price1 * quantity;
                }
                TextView grouppriceAccont = (TextView) mHolder.mGroupAccontLay.findViewById(R.id.tv_order_groupAccont);
                TextView goodsAccontTv = (TextView) mHolder.mGroupAccontLay.findViewById(R.id.tv_order_groupAccont_goodsmoney);
                BigDecimal bigDecimal = new BigDecimal(groupPrice);
                double   newGroupPrice   =   bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                goodsAccontTv.setText(" ¥ " + newGroupPrice);
                float allGroupMoney = dataBean.getShipmentMoney() + groupPrice;
                bigDecimal = new BigDecimal(allGroupMoney);
                double   newAllGroupMoney   =   bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                grouppriceAccont.setText(" ¥ " + newAllGroupMoney);
                // 备注
                final EditText remarkEt = (EditText) mHolder.mGroupAccontLay.findViewById(R.id.et_order_msg);
                remarkEt.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent event) {
                        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
                        if ((view.getId() == R.id.et_order_msg && canVerticalScroll(remarkEt))) {
                            view.getParent().requestDisallowInterceptTouchEvent(true);
                            if (event.getAction() == MotionEvent.ACTION_UP) {
                                view.getParent().requestDisallowInterceptTouchEvent(false);
                            }
                        }
                        return false;
                    }
                });
                remarkEt.setTag(groupPosition);
                remarkEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }
                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }
                    @Override
                    public void afterTextChanged(Editable remark) {
                        int groupPositiopn= (int) remarkEt.getTag();
                        if(!TextUtils.isEmpty(remark)) {
                            shopSelectList.get(groupPositiopn).setNvc_Remarks(remark.toString());
                        }
                    }
                });
            }else{
                mHolder.mGroupAccontLay.setVisibility(View.GONE);
            }
            return convertView;
        }
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
        // 父View的Holder
        class GroupHolder {
            TextView mShopingNameTv;
        }
        // 子View的Holder
        class ItemHolder {
            ImageView mIndentIv;
            TextView mNumberTv;
            TextView mShopingCartTitleTv;
            TextView mStandardTv;
            TextView mShowMoneyTv;
            TextView myOldMoney;
            LinearLayout mGroupAccontLay;
        }
    }
    private float setShipMoney(String cityName){
        float groupShipMoney=0;
        if(TextUtils.isEmpty(cityName)) {
            return groupShipMoney;
        }
        for (int m = 0; m < shopSelectList.size(); m++) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = shopSelectList.get(m).getCartItems();
            String cityNameM = shopSelectList.get(m).getCityName();
            for (int n = 0; n < cartItems.size() ; n++) {
                if(cityName.equals(cityNameM)) {//同城
                    cartItems.get(n).setTongcheng(true);
                    cartItems.get(n).setPianyuan(false);
                    cartItems.get(n).setNomal(false);
                }else if( meArrayList.contains(cityName)){// 如果输入的地址和偏远地区的地址一致,则为偏远地区运费
                    cartItems.get(n).setPianyuan(true);
                    cartItems.get(n).setTongcheng(false);
                    cartItems.get(n).setNomal(false);
                }else{
                    cartItems.get(n).setNomal(true);
                    cartItems.get(n).setTongcheng(false);
                    cartItems.get(n).setPianyuan(false);
                }
            }

        }
        for (int i = 0; i < shopSelectList.size(); i++) {
            List<MeShoppingCartBean.DataBean.CartItemsBean> mscData = shopSelectList.get(i).getCartItems();
            // 获取到重量
            double weight = 0;
            float cityMoney = 0;
            int count = 0;
            float groupprice=0;
            float groupTotalPrice=0;
            //子项
            for (int j = 0; j < mscData.size(); j++) {
                int number = mscData.get(j).getQuantity();
                double childweight = mscData.get(j).getWeight()*number;
                double user_price = mscData.get(j).getUser_price();
                groupTotalPrice += StrUtil.floatNumDeal((float) (number * user_price));
                if (mscData.get(j).isB_BaoYou()) {
                    number = 0;
                    childweight = 0;
                }
                count += number;
                weight += childweight;
                groupprice += StrUtil.floatNumDeal((float) (number * user_price));
            }
            if(weight==0 || count==0){//包邮
                cityMoney=0;
                shopSelectList.get(i).setShipmentMoney(cityMoney);
                groupShipMoney += cityMoney;
            }
            else  if (mscData.get(0).isTongcheng()) {   // 如果输入的地址和店家的地址一致,则为本地运费
                if (weight > 1) {    // 如果重量大于1
                    cityMoney = (float) (8 + Math.ceil(weight - 1) * 2);
                } else {            // 如果重量不大于1,则为首重
                    cityMoney += 8;
                }
                shopSelectList.get(i).setShipmentMoney(cityMoney);
                groupShipMoney += cityMoney;
            } else if (mscData.get(0).isPianyuan()) {
                if (weight > 1) {    // 如果重量大于1
                    cityMoney = (float) (20 + Math.ceil(weight - 1) * 6);
                } else {            // 如果重量不大于1,则为首重
                    cityMoney += 20;
                }
                shopSelectList.get(i).setShipmentMoney(cityMoney);
                groupShipMoney += cityMoney;

            } else {
                if (weight > 1) {    // 如果重量大于1
                    cityMoney = (float) (14 + Math.ceil(weight - 1) * 4);
                } else {            // 如果重量不大于1,则为首重
                    cityMoney += 14;
                }
                shopSelectList.get(i).setShipmentMoney(cityMoney);
                groupShipMoney += cityMoney;
            }
            shopSelectList.get(i).setGroupPriceMoney(groupprice+groupShipMoney);
            shopSelectList.get(i).setGroupTotalPrice(groupTotalPrice);
        }
        groupShipMoney = StrUtil.floatNumDeal(groupShipMoney);
        return groupShipMoney;
    }
    /**
     *  private int AddressID;           //地址Id
     private int I_Id;                   //订单主键                                    ()
     private int Invoice;                //是否开发票  0不需要 1需要                     #
     private String InvoiceTitle;        //发票抬头                                     #
     private int InvoiceType;            //发票类型    0普通发票 1增值税发票              #
     private int MemberID;               //用户Id                                       #
     private String OrderNumber;         //订单编号                                      ()
     private String PSTime;              //配送时间                                      #
     private String PSWay;               //配送方式                                      #
     private String PayWay;              //支付方式                                      #
     private String VAInvoce;             //增值税发票                                   ()
     private double dm_HuoDongAmt;        //全商城首单活动优惠价                          --
     private double dm_PayMoney;          //实收总计                                     #
     private double dm_TotalMoney;        //应收总计                                     #
     private String dt_AddTime;            //订单提交时间                                --
     private String dt_TradeTime;          //支付交易时间                                --
     private int i_ClientType;             //客户端类型 0=PC 1=手机                      #
     private int i_TotalPayInt;           //总的支付积分                                 --
     private int i_TotalReturnInt;        //返的支付积分                                 --
     private String nvc_AliOrderNumber;   //支付交易号（自动生成）                        --
     private String nvc_CardNumber;        //支付账号                                    --
     private String nvc_name2;             //纳税人识别码                               #
     private String nvc_name3;             //注册地址                                   #
     private String nvc_name4;             //注册电话                                   #
     private String nvc_name5;             //开户银行                                   #
     private String nvc_name6;             //银行账户                                   #
     private String nvc_name7;             //收票人姓名                                 #
     private String nvc_name8;             //收票人手机                                 #
     private String nvc_name9;             //收票人地址                                 #
     "dm_OtherMoney": "0",                                                                       #
     "dm_PSMoney": "14.00",                                                                      #
     "dm_RealPay": "25.52",                                                                      #
     "dm_SumMoney": "25.52",                                                                     #
     "i_BusinessId": 30,                                                                         #
     "i_OrdersState": "1",  0.已提交 1.已付款，待确认 2.确认付款,待发货                             ()
     3.已发货,待收货 4.已收货,已完成 5.已取消
     "i_OrdersType": "0",  订单类型（0=普通订单，1=团购订单，2=限时特卖订单）                        #
     "nvc_PSNumber": "",                                                                         ()
     "nvc_PSWay": "快递配送",                                                                    #
     "nvc_Remarks": ""   备注
     "b_Complaint": "false",                      //是否投诉                                          #
     "b_Exchange": "false",                       //是否换货                                          #
     "b_Return": "false",                         //是否退货                                          #
     "dm_SinglePrice": "11.52",                   //产品单价                                          #
     "i_BuyNumber": 1,                            //产品数量                                          #
     "i_OrderComment": "0",                       //是否已评价                                        #
     "i_ProductId": 92,                           //产品ID                                            #
     "i_Promotion": 1,                            //促销类型                                           #
     "i_SingleIntegral": 0,                       //单品积分                                           #
     "nvc_ProductName": "【子约】折页西式邀请函婚礼喜品婚礼请柬", //产品名称                               #
     "nvc_ProductNumber": "108716051911440092",   //产品编号                                           #
     "nvc_ProductPicMain": "http://img1.66wedding.com/Product//Main//300X200//92//d2c14eba-d165-4074-bcf3-d7ff7d89ee1d.jpg" #
     */
    public synchronized void createOrder(){
        Gson gson = new Gson();
        OrderBeanIos orders=new OrderBeanIos();
        OrderBeanIos.OrderBean orderBean = new OrderBeanIos.OrderBean();
        orderBean.setAddressID(addressId);
        orderBean.setInvoice(String.valueOf(invoce));
        orderBean.setInvoiceTitle(invoiceTitle);
        orderBean.setInvoiceType(String.valueOf(invocetype));
        orderBean.setMemberID(String.valueOf(memberID));
        orderBean.setPSTime(peisongTime);
        orderBean.setPSWay(peisongDisc);
        orderBean.setPayWay(payAway);
        orderBean.setDm_PayMoney(StrUtil.floatNumDeal((double) newTotalPrice));
        orderBean.setDm_TotalMoney(StrUtil.floatNumDeal((double) newTotalPrice));
        orderBean.setI_ClientType(String.valueOf(1));
        orderBean.setVAInvoce(invoiceTitle);
        orderBean.setNvc_name2(nvc_name2);
        orderBean.setNvc_name3(nvc_name3);
        orderBean.setNvc_name4(nvc_name4);
        orderBean.setNvc_name5(nvc_name5);
        orderBean.setNvc_name6(nvc_name6);
        orderBean.setNvc_name7(nvc_name7);
        orderBean.setNvc_name8(nvc_name8);
        orderBean.setNvc_name9(nvc_name9);
        List<OrderBeanIos.OrdersBean> ordersList = new ArrayList<OrderBeanIos.OrdersBean>();
        for (int i = 0; i < shopSelectList.size(); i++) {
            MeShoppingCartBean.DataBean groupBean = shopSelectList.get(i);
            OrderBeanIos.OrdersBean groupOrdersBean = new OrderBeanIos.OrdersBean();
            groupOrdersBean.setDm_OtherMoney(String.valueOf(0));
            groupOrdersBean.setDm_PSMoney(StrUtil.floatNumDeal((double) (groupBean.getShipmentMoney())));
            groupOrdersBean.setDm_RealPay(StrUtil.floatNumDeal((double) (groupBean.getGroupTotalPrice()+groupBean.getShipmentMoney())));
//            groupOrdersBean.setDm_SumMoney(String.valueOf(StrUtil.floatNumDeal(groupBean.getGroupTotalPrice()+groupBean.getShipmentMoney())));
            groupOrdersBean.setDm_SumMoney(StrUtil.floatNumDeal((double) (groupBean.getGroupTotalPrice()+groupBean.getShipmentMoney())));
            groupOrdersBean.setI_BusinessId(groupBean.getBusinessID());
            groupOrdersBean.setI_OrdersType(String.valueOf(0));
            groupOrdersBean.setI_OrdersType(String.valueOf(0));
            groupOrdersBean.setNvc_PSNumber("");
            groupOrdersBean.setNvc_PSWay(peisongDisc);
            groupOrdersBean.setNvc_Remarks(groupBean.getNvc_Remarks());
            List<MeShoppingCartBean.DataBean.CartItemsBean> cartItems = groupBean.getCartItems();
            List<OrderBeanIos.OrdersBean.OrderDetailsBean>  orderDetails=new ArrayList<OrderBeanIos.OrdersBean.OrderDetailsBean>();
            for (int j = 0; j < cartItems.size(); j++) {
                MeShoppingCartBean.DataBean.CartItemsBean cartItemsBean = cartItems.get(j);
                OrderBeanIos.OrdersBean.OrderDetailsBean orderDetailsBean=new OrderBeanIos.OrdersBean.OrderDetailsBean();
                orderDetailsBean.setB_Complaint(String.valueOf(false));
                orderDetailsBean.setB_Exchange(String.valueOf(false));
                orderDetailsBean.setB_Return(String.valueOf(false));
                orderDetailsBean.setDm_SinglePrice(StrUtil.floatNumDeal(cartItemsBean.getUser_price()));
                orderDetailsBean.setI_BuyNumber(cartItemsBean.getQuantity());
                orderDetailsBean.setI_OrderComment(String.valueOf(0));
                orderDetailsBean.setI_ProductId(cartItemsBean.getGoods_id());
                orderDetailsBean.setI_Promotion(1);
                orderDetailsBean.setI_SingleIntegral(0);
                orderDetailsBean.setNvc_ProductName(cartItemsBean.getTitle());
                orderDetailsBean.setNvc_ProductNumber(cartItemsBean.getGoods_no());
                orderDetailsBean.setNvc_ProductPicMain(cartItemsBean.getImg_url());
                orderDetails.add(orderDetailsBean);
            }
            groupOrdersBean.setOrderDetails(orderDetails);
            ordersList.add(groupOrdersBean);
        }
        orders.setOrders(ordersList);
        orders.setOrder(orderBean);
        String jsonInfo = gson.toJson(orders);
        String MD5Info="MemberID="+memberID+"&Invoice="+invoce+"&dm_TotalMoney="+StrUtil.floatNumDeal((double) newTotalPrice)
                +"&i_ClientType="+String.valueOf(1)+"&dm_PayMoney="+StrUtil.floatNumDeal((double) newTotalPrice)+
                "&PayWay="+payAway+"&PSWay="+peisongDisc;
        String md5String = MD5Util.getMD5String(MD5Info);
        //POST WeddingMobileApi/CreateOrderByMember?Token={Token}&OrderJson={OrderJson}&signString={signString}
        String url=RequestCode.CreateOrderByMember;
        Log.e("Log", "MeCompileActivity createOrder: url="+url+"jsonInfo="+jsonInfo );
        try {
            jsonInfo = URLEncoder.encode(jsonInfo, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url += "&OrderJson="+jsonInfo+"&signString="+md5String;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, OrderResultBean.class, RequestCode.CreateOrderByMember);
        HttpHandleUtil.executeCommonPost(this,httpRequestBean);
    }
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {

            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }
    private void startPayActivity() {
        if(orderResultBean==null) {
            CUtils.showToast("数据异常，请稍后重试");
            return;
        }
        if ("在线支付".equals(mPayTv.getText())) {
            Intent intent = new Intent(this,MePayActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("order",orderResultBean);
            intent.putExtras(bundle);
            startActivity(intent);

        } else {
            Intent intent = new Intent(this,MeBelowPayActivity.class);
            startActivity(intent);
        }

    }
}
